mybatis 入门进阶之 pojo
有时候我们dao方法声明的入参需要是自定义的pojo,以满足复杂的查询条件。
IWebUserCustomDao.java
package com.mozi.dao; import java.util.List; import com.mozi.entity.WebUser; import com.mozi.entity.WebUserCustom; public interface IWebUserCustomDao { public List<WebUser> findUserList(WebUserCustom userQueryVo); }
sqlmap\userCustomMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace命名空间,作用就是对sql进行分类化的管理,理解为sql隔离 注意:使用mapper代理开发时,namespace有特殊作用 --> <mapper namespace="com.mozi.dao.IWebUserCustomDao"> <select id="findUserList" parameterType="com.mozi.entity.WebUserCustom" resultType="com.mozi.entity.WebUser" > select * from WebUsers <where> <if test ="enable!=null"> Enable = #{enable} </if> <if test ="enable==null"> Enable is NULL </if> </where> </select> </mapper>
同事statment中用到了动态sql : where ,if 。
测试类WebUserCustomDaoImplTest.java
package com.mozi.test.java; import static org.junit.Assert.*; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import com.mozi.dao.IWebUserCustomDao; import com.mozi.dao.IWebUserDao; import com.mozi.dao.impl.WebUserDaoMybatis3; import com.mozi.entity.WebUser; import com.mozi.entity.WebUserCustom; public class WebUserCustomDaoImplTest { private static SqlSessionFactory sqlSessionFactory = null; static{ String resource = "SqlMapConfig.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test public void findUserListTest() { SqlSession sqlSession=null; sqlSession=sqlSessionFactory.openSession(); //生成代理类 IWebUserCustomDao userMapper=sqlSession.getMapper(IWebUserCustomDao.class); //创建包装对象,设置查询条件 WebUserCustom userCustom=new WebUserCustom(); userCustom.setEnable(true); List<WebUser> list = userMapper.findUserList(userCustom); System.out.println(list); sqlSession.close(); } }